/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { BaseElement, element } from '../BaseElement';
import { LitDateRangePane } from './LitDateRangePane';
import './LitDateRangePane';
import { LitDatePane } from './LitDatePane';
import './LitDatePane';
import { LitButton } from '../button/LitButton';
import '../button/LitButton';
import { LitPopover } from '../popover/LitPopoverV';
import '../popover/LitPopoverV';

export const toParseDate = (dateStr: string) => {
  let pickerDate = new Date(dateStr);
  return [pickerDate.getFullYear(), pickerDate.getMonth() + 1, pickerDate.getDate()];
};

export const getParseDateStr = (dateStr: string, dateType = 'date') => {
  let pickerDate = toParseDate(dateStr);
  switch (dateType) {
    case 'date':
      return pickerDate[0] + '-' + (pickerDate[1] + '').padStart(2) + '-' + (pickerDate[2] + '').padStart(2);
    case 'month':
      return pickerDate[0] + '-' + (pickerDate[1] + '').padStart(2);
    default:
      return pickerDate[0] + '';
  }
};

@element('lit-datepicker')
export class LitDatePicker extends BaseElement {
  currentDateValue: any;
  private litPopover: LitPopover | undefined;
  private litPopContent: HTMLDivElement | undefined;
  private dateSelectBtn: LitButton | undefined;
  private dateTextSpan: HTMLSpanElement | undefined;
  private dateCancelBtn: LitButton | undefined;
  private dateSubmitBtn: LitButton | undefined;
  private datePaneEl: any | undefined;
  private isSubmitClick: boolean = false;

  static get observedAttributes() {
    return ['disabled', 'dateType', 'direction', 'minDate', 'maxDate'];
  }

  get minDate() {
    return this.getAttribute('minDate') || '';
  }

  set minDate(minValue: string) {
    this.setAttribute('minDate', minValue);
  }

  get maxDate() {
    return this.getAttribute('maxDate') || '';
  }

  set maxDate(maxValue: string) {
    this.setAttribute('maxDate', maxValue);
  }

  set currentValue(currentValue: any) {
    this.currentDateValue = currentValue;
    this.dateTextSpan!.textContent = this.isRangeDate ? this.currentDateValue.join(' ~ ') : this.currentDateValue;
    if (this.isSubmitClick && !this.isRangeDate && this.datePaneEl) {
      this.datePaneEl.values = this.currentDateValue;
    } else {
      if (this.datePaneEl) {
        this.datePaneEl.values = this.currentDateValue;
      } else {
        this.defaultDateValue = this.isRangeDate ? this.currentDateValue.join('~') : this.currentDateValue;
      }
    }
  }

  get dateType() {
    return this.getAttribute('dateType') || '';
  }

  set dateType(typeValue: string) {
    this.setAttribute('dateType', typeValue);
  }

  get disabled() {
    return this.hasAttribute('disabled');
  }

  set disabled(isShow: boolean) {
    if (isShow) {
      this.setAttribute('disabled', '');
    } else {
      this.removeAttribute('disabled');
    }
  }

  get direction() {
    return this.getAttribute('direction') || '';
  }

  set direction(directionValue: string) {
    this.setAttribute('direction', directionValue);
  }

  get defaultDateValue() {
    let defaultDateValue = this.getAttribute('defaultDateValue');
    if (this.isRangeDate) {
      if (defaultDateValue) {
        let dateArr = defaultDateValue.split('~');
        if (new Date(dateArr[0]) > new Date(dateArr[1])) {
          return [dateArr[1], dateArr[0]];
        } else {
          return dateArr;
        }
      } else {
        return [new Date(), new Date()];
      }
    } else {
      return defaultDateValue || new Date();
    }
  }

  set defaultDateValue(defaultValue: any) {
    this.setAttribute('defaultDateValue', defaultValue);
    if (this.datePaneEl) {
      this.datePaneEl.defaultDateValue = this.defaultDateValue;
    }
  }

  get isRangeDate() {
    return this.hasAttribute('rangeDate');
  }

  get date() {
    if (this.isRangeDate) {
      return this.currentDateValue.map((element: any) => new Date(element));
    } else {
      return new Date(this.currentDateValue);
    }
  }

  initElements(): void {
    this.litPopover = this.shadowRoot?.querySelector('#popover') as LitPopover;
    this.litPopContent = this.shadowRoot?.querySelector('.date-select-context') as HTMLDivElement;
    this.dateSelectBtn = this.shadowRoot?.querySelector('#select') as LitButton;
    this.dateTextSpan = this.shadowRoot?.querySelector('#dateTextSpan') as HTMLSpanElement;
    this.dateCancelBtn = this.shadowRoot?.querySelector('#btn-cancel') as LitButton;
    this.dateSubmitBtn = this.shadowRoot?.querySelector('#btn-submit') as LitButton;
    let dateCancelBtnBtn = this.shadowRoot?.querySelector('.cancelOptionBtn') as LitButton;

    dateCancelBtnBtn.addEventListener('click', () => {
      // @ts-ignore
      this.litPopover.shadowRoot!.querySelector('.trigger-click')!.checked = false;
      this.litPopContent!.style.display = 'none';
    });

    let insideDiv = this.dateSelectBtn!.shadowRoot?.getElementById('custom-div') as HTMLDivElement;
    insideDiv.style.width = '100%';
    insideDiv.style.height = '100%';
    insideDiv.style.padding = '0';

    let insideButton = this.dateSelectBtn!.shadowRoot?.getElementById('custom-button') as HTMLButtonElement;
    insideButton.style.width = '100%';
    insideButton.style.height = '100%';
    insideButton.style.padding = '0 6px 0 15px';
    insideButton.style.border = '1px solid #d9d9d9';
    insideButton.style.borderRadius = '4px';
    insideButton.style.color = '#000';

    this.dateSelectBtn!.addEventListener('mouseenter', () => {
      insideButton.style.border = '1px solid #5B8FF9';
      insideButton.style.color = '#5B8FF9';
    });

    this.dateSelectBtn!.addEventListener('mouseout', () => {
      insideButton.style.border = '1px solid #d9d9d9';
      insideButton.style.color = '#000';
    });
    this.dateSelectBtn!.addEventListener('click', () => {
      this.litPopContent!.style.display = 'table-caption';
      if (!this.datePaneEl) {
        if (this.isRangeDate) {
          this.datePaneEl = new LitDateRangePane();
        } else {
          this.datePaneEl = new LitDatePane();
        }
        this.minDate && (this.datePaneEl.minDate = this.minDate);
        this.maxDate && (this.datePaneEl.maxDate = this.maxDate);
        this.datePaneEl.dateType = this.dateType;
        this.datePaneEl.value = this.defaultDateValue;
        this.litPopContent!.prepend(this.datePaneEl);
      }
    });
    this.dateSubmitBtn!.addEventListener('click', () => {
      this.isSubmitClick = true;
      this.currentValue = this.datePaneEl.value.map((it: any) => it.replace(/\s/g, ''));
      // @ts-ignore
      this.litPopover.shadowRoot!.querySelector('.trigger-click')!.checked = false;
      this.litPopContent!.style.display = 'none';
      let date = this.currentDateValue;
      this.dispatchEvent(
          new CustomEvent('date_change', {
            detail: {
              startTime: date[0],
              endTime: date[1],
            },
          })
      );
    });
    document.addEventListener('click', (ev) => {
      if (!ev.relatedTarget) {
        // @ts-ignore
        this.litPopover.shadowRoot!.querySelector('.trigger-click')!.checked = false;
        this.litPopContent!.style.display = 'none';
      }
    });
    this.currentValue = this.defaultDateValue;
    this.currentDateValue = this.defaultDateValue;
  }

  clearDatePickerContent() {
    // @ts-ignore
    this.litPopover.shadowRoot!.querySelector('.trigger-click')!.checked = false;
    this.litPopContent!.style.display = 'none';
  }

  focus() {
    this.dateSelectBtn!.focus();
  }

  initHtml(): string {
    return `<style>
        :host{
            display:inline-block;
            font-size: 14px;
            line-height: 1.62rem;
            margin-left: 24px;
        }
        :host([block]){
            display: block;
        } 
   
        :host(:focus-within) .popover,:host(:hover) .popover{ 
            z-index: 4;
        }
        :host([disabled]){
            pointer-events: none;
        }
        .popover{
            width: 100%;
            height: 100%;
            display: block;
        }
        #select{
            display: flex;
            width: 100%;
            height: 100%;
            font-size: inherit;
            border: 0;
        }
        #select span{
            flex: 1;
            text-align: left;
        }
        .icon{
            opacity: 0.6;
            border: 0;
        }

        .date-select-context {
            display: table-cell;
            justify-content: flex-end;
            padding: 0 0.42em 0.42em;
            min-width: 100%;
            border: 0;
        }
        
        :host([rangeDate]) .date-select-context{
             display: table-caption;
        }       
         
        .date-select-context .optionBtn{
            font-size: 0.82em;
            margin-left: 0.82em;
            width: 60px;
            height: 30px;
            background: none;
            outline: 0;
            border: 1px solid #d9d9d9;
            inset: 0;
            user-select: none;
            cursor: unset;
            border-radius: inherit;
            float: right;
        }
        
        .optionBtn {
            margin-top: 1.2em
        }
        
        .date-select-context .okOptionBtn {
            background-color: #5B8FF9;
            color: #fff;
        }
        
        .date-select-context .cancelOptionBtn:hover {
           border: 1px solid #5B8FF9;
           color: #5B8FF9;
        }
        
        .date-select-context .okOptionBtn:hover {
           opacity: 0.8;
        }
        
        </style>
        <lit-popover direction="bottomLeft" placement="bottomLeft" trigger="click" id="popover" 
                style="display: block;width: 100%;height: 100%">
            <lit-button id="select" style="display: block;width: 100%;height: 100%;overflow: hidden;">
                <span id="dateTextSpan"></span>
                <lit-icon class="icon" size="24" name="calendar-visit"></lit-icon>
            </lit-button>
            <div slot="content" class="date-select-context">
                <button class="optionBtn okOptionBtn" id="btn-submit">确 认</button>
                <button class="optionBtn cancelOptionBtn">取 消</button>
            </div>
        </lit-popover>`;
  }

  attributeChangedCallback(name: string, oldValue: string, newValue: string) {
    switch (name) {
      case 'disabled':
        if (newValue != null) {
          this.dateSelectBtn!.setAttribute('disabled', 'disabled');
        } else {
          this.dateSelectBtn!.removeAttribute('disabled');
        }
        break;
      case 'minDate':
        if (newValue !== null) {
          this.datePaneEl!.minDate = newValue;
        }
        break;
      case 'maxDate':
        if (newValue !== null) {
          this.datePaneEl!.maxDate = newValue;
        }
        break;
      case 'dateType':
        if (newValue !== null) {
          this.datePaneEl!.dateType = newValue;
        }
        break;
      default:
        break;
    }
  }
}
